import defaultAvatar from '@/assets/SzauKZv.png'
import imgErr from '@/assets/imgErr.png'


const isNumber = (nubmer) => {
    var re = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 //判断正整数 /^[1-9]+[0-9]*]*$/
    return re.test(nubmer)
}

const isNull = (str) => {
    return str == undefined || str == "" || str == null
}

/**
 *
 * @param array 数组
 * @param idFieldName 实际值字段名称
 * @param textFieldName  显示值名称
 * @param idValue 传入实际值
 * @param defaultTextValue 未匹配到的默认显示值
 * @returns {*}
 * @private 从数组中根据实际值获取显示值
 */
const getText = (array, idFieldName, textFieldName, idValue, defaultTextValue) => {

    for (let i = 0; i < array.length; i++) {
        let obj = array[i]
        if (obj[idFieldName] == idValue) {
            return obj[textFieldName]
        }
    }
    return isNull(defaultTextValue) ? "" : defaultTextValue
}

const __getTreeText = (array, idFieldName, textFieldName, idValue) => {
    let text
    for (let i = 0; i < array.length; i++) {
        let p = array[i]
        if (p[idFieldName] === idValue) {
            text = p[textFieldName]
            return text
        }
        if (p.children) {
            text = __getTreeText(p.children, idFieldName, textFieldName, idValue)
            if (text) return text
        }
    }
}
/**
 *
 * @param array 树数组
 * @param idFieldName 实际值字段名称
 * @param textFieldName  显示值名称
 * @param idValue 传入实际值
 * @param defaultTextValue 未匹配到的默认显示值
 * @returns {*}
 * @private 从树中根据实际值获取显示值
 */
const getTreeText = (array, idFieldName, textFieldName, idValue, defaultTextValue) => {
    let text = __getTreeText(array, idFieldName, textFieldName, idValue)
    if (text) {
        return text
    } else {
        return isNull(defaultTextValue) ? "" : defaultTextValue
    }
}

const __treeToArray = (array, tree) => {
    for (let i = 0; i < tree.length; i++) {
        let p = tree[i]
        array.push(p)
        if (p.children) {
            __treeToArray(array, p.children)
        }
    }
}

/**
 * 把数转化为array
 * @param tree
 * @returns {Array}
 * @private
 */
const treeToArray = (tree) => {
    let array = []
    __treeToArray(array, tree)
    return array
}

const getPath = (options, ancestor = []) => {
    let flatOptions = []
    options.forEach((option) => {
        const optionsStack = ancestor.concat(option.id)
        if (!option["children"]) {
            flatOptions.push(optionsStack)
        } else {
            flatOptions.push(optionsStack)
            flatOptions = flatOptions.concat(getPath(option["children"], optionsStack))
        }
    })
    return flatOptions
}

/**
 * 获取数子节点全路径
 * @param tree
 * @param id
 * @private
 */
const getTreePath = (tree, id) => {
    let path = []
    getPath(tree).forEach((op) => {
        for (let i = op.length - 1; i >= 0; i--) {
            let obj = op[i]
            if (obj === id) {
                path = op
                break
            }
        }
    })
    return path
}

const disableTreeNode = (tree, id) => {
    if (tree) {
        id = Number(id)
        for (let i = 0; i < tree.length; i++) {
            let option = tree[i];
            if (option["id"] === id) {
                option["disabled"] = true
                break
            } else {
                disableTreeNode(option["children"], id)
            }
        }
    }

}


/* 格式化文件大小 */
const fileSize = (bytes) => {
    var unit = 'B'
    if (bytes > 1024) {
        bytes /= 1024
        unit = 'KB'
    }
    if (bytes > 1024) {
        bytes /= 1024
        unit = ' MB'
    }
    return Number(bytes.toFixed(1)) + ' ' + unit
}

/* 生成当前时间戳对应的62进制形式短链接 */
const shorten = () => {
    let DIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
    let seq = new Date().getTime()
    let len = DIGITS.length
    let arr = []
    do {
        arr.unshift(DIGITS.charAt(seq % len))
        seq = parseInt(seq / len)
    } while (seq !== 0)
    return arr.join('')
}

function deleteNullChildrenAttr(tree) {
    for (var i in tree) {
        if (tree[i].children) {
            if (tree[i].children.length === 0) {
                delete tree[i].children;
            } else {
                deleteNullChildrenAttr(tree[i].children);
            }
        }
    }
}

function imgError(e, imgSrc) {
    let img = e.srcElement;
    if (imgSrc) {
        img.src = imgSrc;
    } else {
        img.src = imgErr;
    }
    img.onerror = null; //防止闪图
}

function avatorError(e) {
    imgError(e, defaultAvatar)
}

function copy(obj) {
    return JSON.parse(JSON.stringify(obj))
}

function getAncestors(ref, currentId) {
    let checkedNodes = ref.getCheckedNodes();
    let path = []
    if (checkedNodes && checkedNodes.length > 0) {
        path = checkedNodes[0].pathValues
    }
    return [].concat(path).concat(currentId).join(",");
}

function renderSize(value) {
    if (null == value || value === '' || value === 0) {
        return "0 Bytes";
    }
    let unitArr = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
    let index = 0;
    let srcsize = parseFloat(value);
    index = Math.floor(Math.log(srcsize) / Math.log(1024));
    let size = srcsize / Math.pow(1024, index);
    size = size.toFixed(2);//保留的小数位数
    return size + unitArr[index];
}


function getParentName(tree, parentId) {
    if (parentId === 0) {
        return '根目录'
    }
    let ar = treeToArray(tree);
    let newar = ar.filter(t => t.id === parentId).map(t => t.name)
    return newar.length > 0 ? newar[0] : '根目录'
}

function getLabel(value, array, op) {
    let defaultOps = {
        value: 'value',
        label: 'label'
    }
    let ops = Object.assign({}, defaultOps, op)
    return array.filter(t => t[ops.value] === value).map(t => t[ops.label]).join("")
}

export default {
    isNumber,
    isNull,
    getText,
    getTreeText,
    getTreePath,
    getLabel,
    getParentName,
    disableTreeNode,
    fileSize,
    shorten,
    treeToArray,
    deleteNullChildrenAttr,
    imgError,
    avatorError,
    renderSize,
    copy,
    getAncestors,
};
